import axios from 'axios'
import router from '@/router'
import env from '../../config/dev.env'
import {Notification, Loading,MessageBox, Message} from 'element-ui'
import system from './api/system'
import travelInfo from './api/travelInfo'
import user from './api/user'
import application from './api/application'
import order from './api/order'
import admin from './api/admin'
import report from './api/report'
import appraise from './api/appraise'
import qs from 'qs'
import {getToken, removeToken} from '@/utils/auth'
import store from '@/store'
// import Cookies from 'js-cookie';

let api = {
  ...system,
  ...travelInfo,
  ...user,
  ...application,
  ...order,
  ...admin,
  ...report,
  ...appraise
}
// 设置请求带上cookie
axios.defaults.withCredentials = true
axios.defaults.crossDomain = true
api.SUCCESS = ['0000', 0]
api.requestURL = window.SITE_CONFIG['apiUrl']// 正式版后端api地址//"http://192.168.197.204:9202/";//"http://localhost:9202/";//
api.access_token = getToken()
api.loginHandle = null // 登录回调函数
api.local = true
api.localURL = '' // http://localhost:8000/
api.loadingCount = 0
api.loading = null
api.remoteDir = env.NODE_ENV === 'production' ? '/portal' : ''

// 统一请求拦截
axios.interceptors.request.use(
  config => {
    config.params = {
      ...config.params
    }
    if (store.state.app.showLoading) {
      store.commit('app/PLUS_LOADING_NUMBER')
    }
    return config
  }
)
// 统一响应拦截
axios.interceptors.response.use(
  response => {
    const { data, code, message } = response.data
    const {showMessage} = response.config
    if (store.state.app.showLoading) {
      store.dispatch('app/setLoading')
    }

    // console.log(res)
    // if the custom code is not 20000, it is judged as an error.
    if (api.SUCCESS.includes(code)) {
      // Message({
      //   message: res.message || 'Error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      return response.data

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;

      // return Promise.reject(new Error(res.message || 'Error'))
    } else if (code == 401) {
      MessageBox.confirm('登录身份已失效,请重新登录!', '提示').then(() => {
        router.replace({
          name: 'Login',
          path: '/login',
          query: {
            redirect: window.vue.$route.path || ''
          }
        })
      })
      removeToken()
    } else {
      if (showMessage) {
        Message({
          message: `${message}`,
          type: 'error',
          duration: 3 * 1000
        })
      }
      return Promise.reject(new Error(message || 'Error'))
    }
  },
  error => {
    if (store.state.app.showLoading) {
      store.dispatch('app/setLoading')
    }
    let {code, msg} = error.response.data
    if (error.response.status === 401) {
      MessageBox.confirm('登录身份已失效,请重新登录!', '提示').then(() => {
        router.replace({
          name: 'Login',
          path: '/login',
          query: {
            redirect: window.vue.$route.path || ''
          }
        })
        removeToken()
      })
      return Promise.reject(error)
    }
    if (error.response.status === 403) {
      msg = '没有权限访问'
    }
    Message({
      message: msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error.response.data)
  }
)

api.reslutSuccess = function (res) {
  // 关闭loading
  let body = res.data
  if (body.data) {
    body.defaultData = body.data
  }
  api.loadingCount--
  if (api.loadingCount <= 0 && api.loading) {
    api.loading.close()
    api.loadingCount = 0
  }

  return body
}

// 公共get方法
api.getRequest = function (url, params, options = {}) {
  let {showMessage = true} = options
  return new Promise((resolve, reject) => {
    options = {
      showLoading: options.showLoading == null ? true : options.showLoading,
      showMessage: showMessage
    }

    if (process.env.NODE_ENV === 'development') {

    }
    let config = {
      headers: {'Content-Type': 'application/x-www-form-urlencoded', 'tenant-id': 1, Authorization: `Bearer ${api.access_token}`},
      xhrFields: {withCredentials: true},
      crossDomain: true,
      ...options
    }
    axios.get(url, {params: params, ...config})
      .then(res => {
        if (!res) return
        resolve(res)
      }, err => {
        resolve(false)
      }).catch(() => {
        resolve(false)
      })
  })
}
// 公共post方法
api.postRequest = function (url, params, isQueryParam, headers = {'Content-Type': 'application/x-www-form-urlencoded'}, options = {}) {
  let {showMessage = true} = options
  return new Promise((resolve, reject) => {
    options = {
      showLoading: options.showLoading == null ? true : options.showLoading,
      showMessage
    }
    if (isQueryParam) {
      for (var i in params) {
        if (typeof (params[i]) === 'string') { url += '&' + i + '=' + params[i] } else { url += '&' + i + '=' + JSON.stringify(params[i]) }
      }
    }

    let config = {
      xhrFields: {withCredentials: true},
      ...options,
      crossDomain: true
    }// application/x-www-form-urlencoded  //application/json
    // if(cancelSource)
    //     config.cancelToken=cancelSource.token;
    if (headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      params = qs.stringify(params, {indices: false})
    }
    axios.post(url,
      params,
      config
    ).then(res => {
      if (!res) return
      resolve(res)
    }, err => {
      reject(err)
    })
  })
}

// 公共delete方法
api.deleteRequest = function (url, params, options = {}) {
  return new Promise((resolve, reject) => {
    options = {
      showLoading: options.showLoading == null ? true : options.showLoading
    }
    if (url.indexOf('?') < 0) { url += '?v=1' } else { url += '&v=1' }

    if (process.env.NODE_ENV === 'development') {

    }
    let config = {
      headers: {'Content-Type': 'application/x-www-form-urlencoded', access_token: api.access_token},
      xhrFields: {withCredentials: true},
      crossDomain: true
    }
    axios.delete(url, {params: params, ...config})
      .then(res => {
        resolve(res)
      }, err => {
        reject(err)
      })
  })
}

api.putRequest = function (url, params, headers = {'Content-Type': 'application/json'}, options = {}) {
  return new Promise((resolve, reject) => {
    // let user = Cookies.get('user');
    // if (!user && url.toLowerCase().indexOf("login")<0) { // 判断cookie是否已经过期
    //     vm.$router.push({name: 'login'});
    //     Notice.warning({
    //         title: '登录过期',
    //         desc: '对不起，登录已经过期！请重新登录'
    //     });
    //     reject();
    //     return;
    // }
    if (url.indexOf('?') < 0) { url += '?v=1' } else { url += '&v=1' }

    if (process.env.NODE_ENV === 'development') {

    }
    let config = {
      headers: {access_token: api.access_token, ...headers},
      xhrFields: {withCredentials: true},
      crossDomain: true
    }
    axios.put(url, params, config)
      .then(res => {
        resolve(res)
      }, err => {
        reject(err)
      })
  })
}

// 上传请求
api.uploadRequest = function (url, params, files) {
  if (url.indexOf('?') < 0) { url += '?v=1' } else { url += '&v=1' }

  let formdata = new FormData()
  for (let i in files) {
    formdata.append('file', files[i])
  }
  for (let j in params) {
    formdata.append(j, params[j])
  }

  let config = {
    headers: {
      'Content-Type': 'multipart/form-data',
      'tenant-id': 1,
      Authorization: `Bearer ${api.access_token}`
    },
    timeout: 1000 * 60 * 5
  }
  return new Promise((resolve, reject) => {
    axios.post(url, formdata, config).then((res) => {
      resolve(res)
    }).catch((res) => {
      console.log(res, 3333333)
      reject(res)
    })
  })
}

// 下载请求
api.downloadRequest = function (url, params, method) {
  if (url.indexOf('?') < 0) { url += '?v=1' } else { url += '&v=1' }
  let config = {
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', Authorization: `Bearer ${api.access_token}`, 'tenant-id': 1},
    xhrFields: {withCredentials: true},
    crossDomain: true,
    responseType: 'blob'
  }
  if (method === 'get') {
    return new Promise((resolve, reject) => {
      axios.get(url, {params: params}, config).then(res => {
        resolve(res)
      }).catch((err) => {
        reject(err)
      })
    })
  } else {
    return new Promise((resolve, reject) => {
      axios.post(url, params, config).then((res) => {
        resolve(res)
      }).catch((res) => {
        reject(res)
      })
    })
  }
}

// 获取tokey
api.getAccessToken = function (params) {
  // user-用户名密码，dingtalk_qr-扫码登录，dingtalk_authcode-钉钉授权码，qy_wechat_code-企业微信 ,
  return new Promise((resolve, reject) => {
    api.postRequest(api.requestURL + 'oauth/get_access_token', params).then((res) => {
      api.access_token = res.data
      resolve(res)
    }).catch((message) => {
      reject(message)
    })
  })
}

// 刷新iframe父页面
api.refleshParent = function () {
  setTimeout(function () {
    var cmd = {"message":"refresh"};
    if(parent)
      parent.postMessage(JSON.stringify(cmd), '*');
  },5000)
}

// 上传文件
api.upload = function (params, files) {
  return api.uploadRequest(api.requestURL + 'dlv/template/importTemplate', params, files)
}

export default api
